﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using blackhouse.WebNemo.Business;
using blackhouse.WebNemo.Business.Users;
using System.Web.UI;
using blackhouse.WebNemo.Business.Groups;
using System.Drawing;
using System.Configuration;

namespace blackhouse.WebNemo.Web {
    public static class WebNemoUtils {

        private static Factory factory = Factory.Instance();

        public static string GetDisplayUser(int userId) {
            INemoUser cu = factory.GetUser(userId);
            if (cu != null) return cu.Name;
            else return userId.ToString();
        }

        public static string GetImageUrl(this GroupRecord record, string column, Size size) {
            return GetImageUrl(record, column, false, size);
        }

        public static string GetImageUrl(this GroupRecord record, string column, bool fillInner, Size size) {
            bool f = ConfigurationManager.AppSettings["NemoImageFriendly"] == "true";
            return GetImageUrl(record, column, fillInner, size, f);
        }

        public static string GetImageUrl(this GroupRecord record, string column, bool fillInner, Size size, bool friendly) {
            string preparedFileName = record.GetString(column + "_name");
            string[] preparedFileName_s = preparedFileName.Split('.');
            for (int xps = 0; xps < preparedFileName_s.Length - 1; xps++) {
                preparedFileName_s[xps] = preparedFileName_s[xps].CleanStringForUrl().ReplaceEx("-", "_");
            }
            preparedFileName = string.Join(".", preparedFileName_s);
            if (friendly)
                return string.Format("/nemo{6}/{0}/{1}/{2}/{3}x{4}-{5}", record.GetGroup().SelectTable, column, record.RecordId, size.Width, size.Height, preparedFileName, fillInner ? "in" : "").ToLower();
            else
                return string.Format("/NemoIdDynamicImage.ashx?table={0}&column={1}&recordId={2}&width={3}&height={4}&file={5}&fillInner={6}", record.GetGroup().SelectTable, column, record.RecordId, size.Width, size.Height, preparedFileName, fillInner ? "1" : "0");
        }

        public static string GetDownloadUrl(this GroupRecord record, string column) {
            bool f = ConfigurationManager.AppSettings["NemoFileFriendly"] == "true";
            return GetDownloadUrl(record, column, f);
        }

        public static string GetDownloadUrl(this GroupRecord record, string column, bool friendly) {
            string fileName = record.GetFileName(column);
            if (friendly)
                return String.Format("/getnemofile/{0}/{1}/{2}/{3}", record.GetGroup().SelectTable, column, record.RecordId, fileName).ToLower();
            else
                return String.Format("/NemoDownloadFile.ashx?table={0}&column={1}&recordId={2}", record.GetGroup().SelectTable, column, record.RecordId, fileName);
        }

    }
}